<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10">
      <div class="mainor_form">
        <div class="mainor_te">
          <el-button @click="editAction()" class="marginLeft10" type="primary"
            >新增客服</el-button
          >
        </div>
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="80px"
        >
          <el-form-item label="客服名称" prop="keyword">
            <el-input
              v-model.trim="form.keyword"
              placeholder="姓名/手机/昵称/账号"
              clearable
              class="wid220"
            ></el-input>
          </el-form-item>

          <el-form-item label="客服角色" prop="cust_role">
            <el-select
              v-model="form.cust_role"
              clearable
              placeholder="客服角色"
            >
              <el-option
                v-for="item in custType"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="客服状态" prop="service_status">
            <el-select
              v-model="form.service_status"
              clearable
              placeholder="客服状态"
            >
              <el-option
                v-for="item in custStatus"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <div class="clearfix"></div>

          <el-form-item class="marginTop10">
            <el-button
              class="reset marginLeft10"
              type="primary"
              @click="reset()"
              >重置</el-button
            >
            <el-button
              type="primary"
              @click="getArticleList"
              :loading="listLoading"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <div class="main_table" style="min-height: 590px">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
        >
          <!-- <el-table-column type="selection" /> -->

          <el-table-column
            label="序号"
            width="100"
            prop="id"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{ scope.row.id }}</template>
          </el-table-column>

          <el-table-column
            label="姓名"
            prop="name"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            label="负责人"
            prop="mobile"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            label="客服角色"
            prop="role"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.role.name }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="客服数量"
            prop="user_num"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.user_num }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="服务状态"
            width="120"
            prop="service_status"
            :show-overflow-tooltip="true"
          >
            <!-- a==0?-1:a==1?0:1#03A98E #F56C6C #409EFF-->
            <template slot-scope="scope">
              <span
                :class="{
                  one: scope.row.service_status == 1,
                  two: scope.row.service_status == 2,
                  three: scope.row.service_status == 3
                }"
              >
                {{
                  scope.row.service_status == 1
                    ? "休息"
                    : scope.row.service_status == 2
                    ? "上班"
                    : "休假"
                }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            label="账号状态"
            width="120"
            prop="status"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span
                :style="{
                  color: scope.row.status == 1 ? '#03A98E' : '#F56C6C'
                }"
              >
                {{ scope.row.status == 1 ? "正常" : "禁用" }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            label="描述"
            :show-overflow-tooltip="true"
            width="120"
            prop="remark"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                @click="editAction(scope.row.id)"
                type="text"
                size="mini"
                style="color:#03a98e"
                class="handle_btn"
                >编辑</el-button
              >
              <el-button
                type="text"
                size="mini"
                style="color:#606266"
                class="handle_btn"
                @click="chatchange(scope.row.id)"
                >聊天记录</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div>
        <el-dialog :visible.sync="custVisible" width="60%" :modal="false">
          <div class="flex1">
            <div class="search">
              <i class="el-icon-search"></i>
              <input type="text" placeholder="搜索" v-model="value" />
              <i v-if="clear" class="el-icon-error"></i>
            </div>

            <div class="cust-left">
              <div class="content-box">
                <div class="c-hight">
                  <div
                    class="list-box"
                    v-for="(item, index) in custlist"
                    :key="index"
                  >
                    <img
                      class="avatar"
                      :src="avatar.img_prefix + item.setting.site_logo"
                    />
                    <div class="dis-flex" @click="select(item)">
                      <div class="avatar-flex">
                        <div class="title">{{ item.name }}</div>
                        <div class="time">
                          {{
                            item.msg_last == null
                              ? ""
                              : calculateTime(item.msg_last.created_at)
                          }}
                        </div>
                      </div>

                      <div class="contents" v-if="item.msg_last == null"></div>

                      <div class="contents" v-if="item.msg_last != null">
                        {{
                          item.msg_last.msg_type == 2
                            ? "[ 图片 ]"
                            : item.msg_last.msg
                        }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="cust-right">
                <div class="name-title">{{ headtxt }}</div>
                <div id="wrapper" class="shight" @scroll="scroll">
                  <div v-if="isend" class="loadmore">正在加载</div>
                  <div class="talk-list">
                    <div v-for="(items, lindex) in talkList" :key="lindex">
                      <div class="time-txt" v-if="items.type === 'addTime'">
                        {{ calculateTime(items.time) }}
                      </div>
                      <div
                        class="item flex_col"
                        :class="items.send_type == 1 ? 'push' : 'pull'"
                      >
                        <img
                          v-if="items.send_type == 1"
                          :src="
                            avatar.img_prefix + items.user.setting.site_logo
                          "
                          class="pic"
                        />
                        <img
                          v-if="items.send_type == 2"
                          :src="avatar.img_prefix + items.cust.head_pic"
                          class="pic"
                        />

                        <div class="content" v-if="items.msg_type == 1">
                          {{ items.msg }}
                        </div>

                        <div class="picture" v-if="items.msg_type == 2">
                          <img :src="avatar.img_prefix + items.msg" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-dialog>
      </div>

      <div class="main_page boxdq">
        <div></div>
        <!-- 分页 -->
        <div class="main_page_r">
          <el-pagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getList, getchatlist, getchatrecord } from "@/api/user/userList";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { weChatTimeFormat } from "@/utils/time";
export default {
  computed: {
    ...mapGetters(["avatar"])
  },

  data() {
    return {
      current: {
        page: 1,
        size: 10
      },
      limit: 20,
      totalCount: 1,
      // 搜索
      form: {},
      // 列表数据
      list: [],
      listLoading: false,
      custStatus: [
        {
          name: "休息",
          id: 1
        },
        {
          name: "上班",
          id: 2
        },
        {
          name: "休假",
          id: 3
        }
      ],
      custType: [],
      custVisible: false,
      value: "",
      clear: false,
      custlist: [],
      uids: "", //初始用户id
      headtxt: "",
      talkList: [],
      count: 0, //总条数
      listpage: {
        page: 1,
        size: 10
      },
      isend: false,
      pos: 0
    };
  },
  mounted() {
    this.getData();
    // window.addEventListener("scroll", this.handleScroll, true);
  },

  methods: {
    //编辑
    editAction(id) {
      if (id) {
        this.$router.push({
          path: "/user/customer/customeredit",
          query: { id, custype: JSON.stringify(this.custType) }
        });
      } else {
        this.$router.push({
          path: "/user/customer/customeradd",
          query: { custype: JSON.stringify(this.custType) }
        });
      }
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.getData();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.getData();
    },

    changePage(page) {
      this.current.page = page;
      this.getData();
    },
    // 获取数据列表
    getData() {
      this.listLoading = true;
      let search = this.form;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, search, this.current)) +
              apiUrl().appsecret
          )
        },
        apiUrl().name,
        search,
        this.current
      );
      getList(data).then(res => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data.list;
          this.custType = res.data.role_list;
          this.totalCount = res.data.count;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },

    //根据客服获取客户列表
    chatchange(id) {
      let data = Object.assign(
        {
          sign: Md5(objKeySort(Object.assign(apiUrl())) + apiUrl().appsecret)
        },
        { id: id }
      );
      getchatlist(data).then(res => {
        if (res.errcode == 0) {
          this.custVisible = true;
          this.custlist = res.data.list;
          let name = res.data.list.length == 0 ? "" : res.data.list[0].name;
          this.headtxt = name;
          if (res.data.list.length != 0) {
            this.uids = res.data.list[0].id;
            this.getdetail(this.uids);
          }
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 获取聊天详情
    getdetail() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        { user_id: this.uids },
        this.listpage
      );
      getchatrecord(data).then(res => {
        if (res.errcode == 0) {
          if (res.data.list.length == 0) {
            this.talkList = [];
          } else {
            let data = res.data.list;
            this.count = res.data.count;
            let messageList = [...data];
            let newList = [];
            let compareTime;
            messageList.forEach((item, index) => {
              if (!compareTime) {
                compareTime = item.created_at;
              } else {
                if (Math.abs(compareTime - item.created_at) < 300) {
                } else {
                  newList.push({
                    type: "addTime",
                    time: messageList[index - 1].created_at
                  });
                  compareTime = item.created_at;
                }
              }
              newList.push(item);
              if (index === messageList.length - 1) {
                newList.push({
                  type: "addTime",
                  time: item.created_at
                });
              }
            });
            newList.reverse();
            this.talkList = newList;
            this.$nextTick(function() {
              let div = document.getElementById("wrapper");
              div.scrollTop = div.scrollHeight;
            });
          }
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    scroll(event) {
      this.pos = event.target.scrollTop;
      if (this.listpage.size < this.count) {
        this.listpage.size += 10;
        this.getdetail(this.listpage);
      } else {
        console.log(111);
      }
    },

    //选择客户查看聊天记录
    select(item) {
      this.headtxt = item.name;
      this.uids = item.id;
      this.listpage.size = 10;
      this.getdetail(item.id, this.listpage);
    },
    //重置表单
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.getData();
    },
    calculateTime(time) {
      return weChatTimeFormat(new Date(time * 1000));
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.maincl {
  .el-select {
    width: 114px;
  }
  .more {
    margin-left: 50px;
  }
  .handle_btn {
    padding: 0;
    border: 0;
  }
  .edit_dialog {
    .address {
      max-width: 350px;
    }
  }

  .mainor_form form {
    // width: calc(100% - 180px);
    width: 100%;
  }

  .main_table /deep/.el-table--small td {
    padding: 10px 0;
  }
  .main_table /deep/.el-table--small th {
    padding: 10px 0;
  }

  /deep/.el-table {
    tr {
      &:hover {
        background: none !important;
      }
      &.hover-row > td {
        background: none !important;
      }
      .current-row > td {
        background: none !important;
      }
    }
  }
  /deep/.el-table .el-table__body tr:hover {
    background: #fff !important;
  }
  /deep/.el-table .el-table__body tr:hover > td {
    background: #fff !important;
  }
  /deep/.el-table tr.expanded + tr {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr > td {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr .mainex_ta {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr .mainex_ta th,
  /deep/.el-table tr.expanded + tr .mainex_ta tr {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr:hover {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr:hover > td {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr .el-table tr:hover {
    background: #fafafa !important;
  }
  /deep/.el-table tr.expanded + tr .el-table tr:hover > td {
    background: #fafafa !important;
  }
  /deep/.el-table .cell {
    display: flex;
    align-items: center;
  }
  /deep/.boxdq {
    justify-content: flex-end;
  }
}
.exptitle {
  padding: 10px 0px;
}
.one {
  color: #03a98e;
}
.two {
  color: #666;
}
.three {
  color: #f56c6c;
}

.flex1 {
  display: flex;
  height: 510px;
  overflow: hidden;
  margin-top: 10px;
}
.search {
  background-color: #f6f6f6;
  position: fixed;
  top: 18%;
  left: 21.5%;
  width: 16%;
  padding: 0px 15px;
  border-radius: 20px;
  display: flex;
  align-items: center;
}
.search input {
  background-color: transparent;
  flex: 1;
  height: 32px;
  line-height: 32px;
  margin: 0px 7px;
}

.el-icon-error {
  font-size: 18px;
}

.cust-left {
  height: auto;
  display: flex;
  width: 100%;
}
.content-box {
  width: 32%;
  height: auto;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.c-hight {
  width: 100%;
  height: 510px;
  overflow-y: auto;
  padding-right: 15px;
}
.list-box {
  width: 100%;
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.avatar {
  width: 42px;
  height: 42px;
  border-radius: 50%;
}
.avatar-flex {
  display: flex;
  height: auto;
  flex: 1;
}
.dis-flex {
  border-bottom: 1px solid #f2f2f2;
  flex: 1;
  margin-left: 10px;
  padding-bottom: 8px;
  overflow: hidden;
}
.title {
  font-size: 14px;
  flex: 1;
  padding-bottom: 6px;
}
.contents {
  font-size: 14px;
  color: #b4b4b4ff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 16px;
}
.time {
  font-size: 14px;
  color: #b4b4b4ff;
}
.cust-right {
  flex: 1;
  margin-left: 20px;
}
.name-title {
  font-size: 16px;
  padding-bottom: 10px;
}
/deep/.el-dialog {
  height: 600px;
  overflow: hidden;
}
.shight {
  width: 100%;
  height: 482px;
  // overflow: hidden;
  // padding-right: 15px;
  overflow-y: auto;
  border: 1px solid #f2f2f2;
}
.talk-list {
  padding-bottom: 10px;
  // height: 882px;
  /* 消息项，基础类 */
  .item {
    padding: 10px 10px 0 10px;
    align-items: flex-start;
    align-content: flex-start;
    color: #333;

    .pic {
      width: 46px;
      height: 46px;
      border-radius: 50%;
      border: #fff solid 1px;
    }

    .content {
      padding: 10px;
      border-radius: 4px;
      max-width: 300px;
      word-break: break-all;
      line-height: 18px;
      position: relative;
    }
    .picture {
      max-width: 22%;
      height: auto;
      img {
        width: 100%;
        height: auto;
      }
    }

    /* 收到的消息 */
    &.pull {
      .content {
        margin-left: 16px;
        background-color: #dcfff9ff;

        &::after {
          content: "";
          display: block;
          width: 0;
          height: 0;
          border-top: 8px solid transparent;
          border-bottom: 8px solid transparent;
          border-right: 10px solid #dcfff9ff;
          position: absolute;
          top: 15px;
          left: -6px;
        }
      }
    }

    /* 发出的消息 */
    &.push {
      /* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
      flex-direction: row-reverse;

      .content {
        margin-right: 16px;
        background-color: #f1f1f1ff;

        &::after {
          content: "";
          display: block;
          width: 0;
          height: 0;
          border-top: 8px solid transparent;
          border-bottom: 8px solid transparent;
          border-left: 10px solid #f1f1f1ff;
          position: absolute;
          top: 15px;
          right: -6px;
        }
      }
    }
  }
}
.time-txt {
  color: #b4b4b4ff;
  text-align: center;
  padding-top: 10px;
}

.flex_col {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
  align-content: center;
}
::-webkit-scrollbar-thumb {
  background-color: #afafafff;
}
::-webkit-scrollbar-track {
  background-color: #e9e9e9ff;
}
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.loadmore {
  height: 35px;
  line-height: 35px;
  text-align: center;
}
</style>
